//
//  ViewController.m
//  QQ_Chat_UI
//
//  Created by ZJ on 2018/7/31.
//  Copyright © 2018年 iCatch Technology Inc. All rights reserved.
//

#import "ViewController.h"
#import "ZJMessageFrame.h"
#import "ZJMessage.h"
#import "ZJMessageCell.h"

static NSString * const ZJMessageCellReuseIdentifier = @"messageCell";

@interface ViewController () <UITableViewDelegate, UITableViewDataSource, UITextViewDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UITextView *inputTextView;
@property (weak, nonatomic) IBOutlet UIButton *sendButton;

@property (nonatomic, strong) NSMutableArray<ZJMessageFrame *> *messageFrames;

@end

@implementation ViewController

#pragma mark - Prepare Data
- (NSMutableArray<ZJMessageFrame *> *)messageFrames {
    if (_messageFrames == nil) {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"messages.plist" ofType:nil];
        NSArray *message = [[NSArray alloc] initWithContentsOfFile:path];
        
        NSMutableArray *messageFramesM = [[NSMutableArray alloc] initWithCapacity:message.count];
        
        [message enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            ZJMessage *message = [ZJMessage messageWithDict:obj];
            
            ZJMessage *lastMessage = (ZJMessage *)[messageFramesM.lastObject message];
            
            // 判断当前模型的“消息发送时间”是否和上一个模型的“消息发送时间”一致， 如果一致做个标记
            if ([message.time isEqualToString:lastMessage.time]) {
                message.hideTime = YES;
            }
            
            message.iconImgName = message.type == ZJMessageTypeMe ? @"me" : @"other";
            
            ZJMessageFrame *msgFrame = [[ZJMessageFrame alloc] init];
            msgFrame.message = message;
            
            [messageFramesM addObject:msgFrame];
        }];
        
        _messageFrames = messageFramesM.mutableCopy;
    }
    
    return _messageFrames;
}

#pragma mark - Life Cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    [self setupGUI];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Setup GUI
- (void)setupGUI {
    // 取消分隔线
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    // 设置UITableView背景颜色
    self.tableView.backgroundColor = [UIColor colorWithRed:236 / 255.0 green:236 / 255.0 blue:236 / 255.0 alpha:1.0];
    
    // 设置UITableView的行不允许被选中
    self.tableView.allowsSelection = NO;
    
    // 注册cell
    [self.tableView registerClass:[ZJMessageCell class] forCellReuseIdentifier:ZJMessageCellReuseIdentifier];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    
    // 监听键盘的弹出事件
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
    
    // 添加tap手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(popKeyboard)];
    [self.view addGestureRecognizer:tap];
    
    self.inputTextView.delegate = self;
    
    [self.sendButton addTarget:self action:@selector(sendButtonClick:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)keyboardWillChangeFrame:(NSNotification *)nc {
    // nc.name      通知的名称
    // nc.object    通知的发布者
    // nc.userInfo  通知的具体内容
    
    CGRect keyboardFrame = [nc.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat keyboardY = CGRectGetMinY(keyboardFrame);
    
    CGFloat tranformValue = keyboardY - CGRectGetHeight(self.view.frame);
    
    [UIView animateWithDuration:0.25 animations:^{
        self.view.transform = CGAffineTransformMakeTranslation(0, tranformValue);
    }];
    
    // 当弹出键盘时把最后一行滚动到最上面
    if (tranformValue < 0) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.messageFrames.count - 1 inSection:0];
        [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
    }
}

- (void)popKeyboard {
    [self.view endEditing:YES];
}

- (void)sendButtonClick:(UIButton *)sender {
    NSString *title = sender.currentTitle;
    
    // 判断当前是否为"发送"按钮
    if (title == nil) {
        return;
    }
    
    // 发送消息
    NSString *text = self.inputTextView.text;
    if (text == nil || [text isEqualToString:@""]) {
        NSLog(@"text is nil or ' '.");
        return;
    }
    
    [self sendMessage:text type:ZJMessageTypeMe];
    
    // 发送一条系统消息
    uint32_t length = (uint32_t)(self.messageFrames.count - 1);
    uint32_t index = arc4random_uniform(length);
    [self sendMessage:self.messageFrames[index].message.text type:ZJMessageTypeOther];
    
    // 清空文本框
    self.inputTextView.text = @"";
    [self textViewDidChange:self.inputTextView];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.messageFrames.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ZJMessageCell *cell = [tableView dequeueReusableCellWithIdentifier:ZJMessageCellReuseIdentifier forIndexPath:indexPath];;
    
    ZJMessageFrame *msgFrame = self.messageFrames[indexPath.row];
    
    cell.messageFrame = msgFrame;
    
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return self.messageFrames[indexPath.row].rowHeight;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    if ([[scrollView class] isSubclassOfClass:[UITextView class]]) {
        return;
    }
    
    [self popKeyboard];
}

#pragma mark - UITextViewDelegate
- (void)textViewDidChange:(UITextView *)textView {
    NSString *text = textView.text;
    
    UIImage *imageNor = nil;
    UIImage *imageHighted = nil;
    NSString *btnTitle = nil;
    if ([text isEqualToString:@""]) {
        imageNor = [UIImage imageNamed:@"chat_bottom_up_nor"];
        imageHighted = [UIImage imageNamed:@"chat_bottom_up_press"];
    } else {
        btnTitle = @"Send";
    }
    
    [self.sendButton setTitle:btnTitle forState:UIControlStateNormal];
    [self.sendButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [self.sendButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
    self.sendButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [self.sendButton setImage:imageNor forState:UIControlStateNormal];
    [self.sendButton setImage:imageHighted forState:UIControlStateHighlighted];
}

- (void)sendMessage:(NSString *)msg type:(ZJMessageType)type {
    if (msg == nil) {
        NSLog(@"msg is nil.");
        return;
    }
    
    ZJMessage *message = [[ZJMessage alloc] init];
    
    NSDate *nowDate = [NSDate date];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"今天 HH:mm";
    
    message.time = [formatter stringFromDate:nowDate];
    message.text = msg;
    message.type = type;
    
    ZJMessageFrame *lastMessageFrame = self.messageFrames.lastObject;
    
    NSString *lastTime = lastMessageFrame.message.time;
    if ([message.time isEqualToString:lastTime]) {
        message.hideTime = YES;
    }
    
    // 设置头像
    message.iconImgName = message.type == ZJMessageTypeMe ? @"me" : @"other";

    ZJMessageFrame *msgFrame = [[ZJMessageFrame alloc] init];
    msgFrame.message = message;
    
    // 把frame 模型加到集合中（注意：要可变数组）
    [self.messageFrames addObject:msgFrame];
    
    // 刷新UITableView的数据
    [self.tableView reloadData];
    
    // 把最后一行滚动到最上面
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.messageFrames.count - 1 inSection:0];
    [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

@end
